#!/usr/bin/env python

import argparse, os, sys, inspect, ConfigParser, daemon

from gui.cGui.controller.CGuiController import CGuiController
from NessusCom.NessusCommunicator import NessusCommunicator
from deliveryMethod.MailSender import MailSender
from ScanEvent.ScanRunner import ScanRunner
from ScanEvent.ScanEvent import ScanEvent
from time import sleep


def processArgs():
    """Uses `argparse <http://docs.python.org/dev/library/argparse.html>`_ to create the command line arguments and subsequent variables/values.
    
    It also loops through the **reportDict** and displays their respective help descriptions sorted by report name.
    
    Returns:
        list of parsed options.
    """
    parser = argparse.ArgumentParser(description='Cernent', prog='cernent')
    
    parser.add_argument('-e', '--example', metavar='report', nargs='+', help='Print report example')
    '''Temporary gui flag, in the future it will default to the gui unless otherwise specified'''
    parser.add_argument('-g', '--gui', action='store_true', help='Run the gui, ignore all other flags.')
    
    #for reportName, report in sorted(reportDict.items()):
    #    parser.add_argument('--%s' % reportName, action='store_true', help=report.getCLIHelp())
        
    return parser.parse_args()

    
def printReportExamples(reports):
    """Loops through the list of reports and shows the example output for each.
    
    Args:
        reports (list): The list of reports to show examples for.
    """
    
    for report in reports:
        print(report)
        if reportDict.has_key(report):
            print(reportDict[report].getExample())
    

def pullConfAndInit(conf):
    
    config = ConfigParser.ConfigParser()
    config.read(conf)
    
    scanners = {}
    mailer = None
    
    for section in config.sections():
        if "scanner" in section:
            scanners[config.get(section, 'name')] = NessusCommunicator(config.get(section, "hostname"),
                                                                       int(config.get(section, "port")),
                                                                       config.get(section, "username"), 
                                                                       config.get(section, 'password'))

        #if "mailer" in section:
        #    mailer = MailSender(config.get(section, 'smtp_server'), config.get(section, 'port'), 
        #                        config.get(section, 'username'), config.get(section, 'password'))
            
            
    return mailer, scanners


def getConfPath():
    conf = os.path.realpath(__file__).split('/')[:-1]
    conf.append('etc')
    conf.append('cernent.conf')
    conf = '/'.join(conf)
    return conf


def exampleScanEvent():
    se = ScanEvent()
    se.setEmailItems(['email1', 'email2'])
    se.setName('Cernent Example Scan')
    se.setPolicy('Default Safe (Cred)')
    se.setReports(['reporta', 'reportb'])
    se.setSchedule('sometime')
    se.setTargets('127.0.0.1')
    se.setTimeToWait('60')
    se.setNessusCommName('Main Scanner')
    
    return se
    

def startScanning(mailer, scanners):
    
    for i in range(1):
        print('ScanRunner')
        se = exampleScanEvent()
        s = ScanRunner(scanners[se.getNessusCommName()], mailer, se)
        s.start()

    while True:
        sleep(60)

def main():
    """Executes CLI if Cerno is run from the command line.
    """
    
    conf = getConfPath()

    mailer, scanners = pullConfAndInit(conf)

    options = processArgs()
    
    if options.gui:
        app = CGuiController(scanners)
        app.show()
    else:
        if options.example:
            printReportExamples(options.example)
        
    #with daemon.DaemonContext():
    startScanning(mailer, scanners)    
        
                
    
    
'''
Runs main as long as script is executed at the command line, looks for and catches
Ctrl-C keyboard interrupts in case the python interpreter or O/S doesn't by default.
'''    
if __name__ == '__main__':
    try:
        main()
    except (KeyboardInterrupt):
        print("^C")
        exit()